﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Proggy.Web.Cms.Core.Seo.Service.Abstract;
using System.IO;

namespace Proggy.Web.Cms.Core.Seo.Service.Concrete
{
    /// <summary>
    /// Basic robots.txt file service
    /// </summary>
    public class RobotsFileService : IRobotsFileService
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="rootFolderPath"></param>
        /// <param name="rootUrl"></param>
        /// <param name="additionalDisallows"></param>
        /// <param name="autoGenerateFile"></param>
        public RobotsFileService(string rootFolderPath, string rootUrl, string[] additionalDisallows, bool autoGenerateFile)
        {
            this.RootFolderPath = rootFolderPath;
            this.RootUrl = rootUrl;
            this.AutoGenerateFile = autoGenerateFile;
            this.AdditionalDisallows = additionalDisallows;
        }

        /// <summary>
        /// Root folder path
        /// </summary>
        public string RootFolderPath { get; set; }

        /// <summary>
        /// If false, when "GenerateRobotsFile()" is called, will do nothing
        /// </summary>
        public bool AutoGenerateFile { get; set; }

        /// <summary>
        /// Additional lines for "disallow"
        /// </summary>
        public string[] AdditionalDisallows { get; set; }

        /// <summary>
        /// Root Url
        /// </summary>
        public string RootUrl { get; set; }

        /// <summary>
        /// Generate file - will do nothing AutoGenerateFile = false
        /// </summary>
        public void GenerateRobotsFile()
        {
            // check
            if (AutoGenerateFile)
            {
                // get string builder
                var builder = new StringBuilder("User-agent: *\n");

                // add defaut disallows
                builder.Append("Disallow: ");
                builder.Append(RootUrl);
                builder.Append("proggy/\n");
                builder.Append("Disallow: ");
                builder.Append(RootUrl);
                builder.Append("proggycore/");

                // add addition
                foreach (var add in AdditionalDisallows) {
                    builder.Append("\nDisallow: ");
                    builder.Append(add);
                }

                // write
                File.WriteAllText(RootFolderPath + "robots.txt", builder.ToString());
            }
        }
    }
}
